import axios from "axios"
import store from "@/store"
import { message } from "antd"
import { customHistory } from "./history"
import { logout } from "@/store/actions"
const http = axios.create({
  baseURL: "http://geek.itheima.net/v1_0",
  timeout: 5000
})
http.interceptors.request.use((config) => {
  const {
    login: { token }
  } = store.getState()
  // startsWith 字符串以什么开头
  if (!config.url.startsWith("/authorizations")) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})
http.interceptors.response.use(
  (response) => response,
  (error) => {
    if (!error.response) {
      message.error("网络繁忙，请稍后再试")
      return Promise.reject(error)
    }
    if (error.response.status === 401) {
      message.error(error.response.data?.message, 1.5, () => {
        // 删除token
        store.dispatch(logout())
        // 跳转到登录页，并携带当前要访问的页面，这样，登录后可以继续返回该页面
        customHistory.push("/login", {
          from: customHistory.location.pathname
        })
      })
    }
  }
)
export { http }
